package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.enjity.PageResult;
import com.itheima.enjity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;//从配置文件中读取要生成的html对应的目录


    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //添加表单基础数据
        setmealDao.addSetmeal(setmeal);
        this.addSetmelIdAndCheckGroupIds(setmeal, checkgroupIds);

        String img = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
        //当添加套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
        System.out.println("前");
        generateMobileStaticHtml();
        System.out.println("hou");
    }

    //生成当前方法所需的静态页面
    private void generateMobileStaticHtml() {
        //在生成静态页面之前需要查询数据
        List<Setmeal> all = setmealDao.findAll();
        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(all);
        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(all);
    }

    private void generateMobileSetmealDetailHtml(List<Setmeal> all) {
        for (Setmeal setmeal : all) {
            Map map = new HashMap();
            map.put("setmeal",setmealDao.findByIds(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

    private void generateMobileSetmealListHtml(List<Setmeal> all) {
        Map map = new HashMap();
        //为模块提供数据，用于生成静态页面
        map.put("setmealList", all);
        generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //通用的方法，用于生成静态页面
    public void generteHtml(String templateName, String htmlPathName, Map map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPathName));
            //输出文件
            template.process(map, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public PageResult queryPage(QueryPageBean queryPagebean) {
        Integer currentPage = queryPagebean.getCurrentPage();
        Integer pageSize = queryPagebean.getPageSize();
        String queryString = queryPagebean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> setmeals = setmealDao.queryPage(queryString);
        return new PageResult(setmeals.getTotal(), setmeals);

    }

    @Override
    public void delelte(Integer id) {
        //删除中间表关联关系
        setmealDao.deleteSermealAndCheckGroup(id);
        //删除当前信息
        setmealDao.deleteSermeal(id);
    }

    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        return setmeal;
    }

    @Override
    public List<Integer> findSetMealIdAndCheckGroupId(Integer id) {
        List<Integer> setMealIdAndCheckGroupId = setmealDao.findSetMealIdAndCheckGroupId(id);
        return setMealIdAndCheckGroupId;
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findByIds(Integer id) {
        return setmealDao.findByIds(id);
    }

    private void addSetmelIdAndCheckGroupIds(Setmeal setmeal, Integer[] checkgroupIds) {
        //添加中间表关联关系
        Integer setmealId = setmeal.getId();
        if (checkgroupIds.length > 0 && checkgroupIds!=null) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setmealDao.addSetmelIdAndCheckGroupIds(map);
            }
        }
    }
}
